/**
 * Project Name:dsrs-systemservice-web
 * File Name:DatadicTypeController.java
 * Package Name:com.bwda.dsrs.systemservice.controller;
 * Date:2019年4月28日
 * Copyright (c) 2019, 江苏保旺达软件有限公司 All Rights Reserved.
 */
package com.bwda.dsrs.systemservice.controller;


import com.bwda.dsrs.base.centerbase.BaseConstants;
import com.bwda.dsrs.base.centerbase.response.CentreCutPageResponse;
import com.bwda.dsrs.base.centerbase.response.CentreListResponse;
import com.bwda.dsrs.base.centerbase.response.ResponseEntity;
import com.bwda.dsrs.base.util.CopyUtil;
import com.bwda.dsrs.common.enums.BusinessStatus;
import com.bwda.dsrs.systemservice.annotations.NeedRole;
import com.bwda.dsrs.systemservice.aspect.LogTypeEnum;
import com.bwda.dsrs.systemservice.aspect.Loggable;
import com.bwda.dsrs.systemservice.domain.Constants;
import com.bwda.dsrs.systemservice.domain.condition.datadictype.DatadicTypeCondition;
import com.bwda.dsrs.systemservice.domain.exception.SystemServiceException;
import com.bwda.dsrs.systemservice.domain.form.datadictype.DatadicTypeCreateForm;
import com.bwda.dsrs.systemservice.domain.form.datadictype.DatadicTypeQueryForm;
import com.bwda.dsrs.systemservice.domain.form.datadictype.DatadicTypeUpdateForm;
import com.bwda.dsrs.systemservice.domain.po.datadictype.DatadicTypePo;
import com.bwda.dsrs.systemservice.domain.vo.datadict.DatadictSelectVo;
import com.bwda.dsrs.systemservice.domain.vo.datadictype.DatadicTypeVo;
import com.bwda.dsrs.systemservice.service.DatadicTypeService;
import com.bwda.dsrs.systemservice.service.DatadictService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 数据字典类别
 *
 * @author liangjianyong
 * @date 2019/4/11
 */
@RestController
@RequestMapping("/s/datadictype")
@Api(value = "/s/datadictype", tags = "数据字典类型")
public class DatadicTypeController extends BaseController {

    @Autowired
    private DatadicTypeService datadicTypeService;

    @Autowired
    private DatadictService datadictService;

    @ApiOperation(value = "查询系统数据字典类型", notes = "查询系统数据字典类型", httpMethod = "GET")
    @Loggable(descp = "查询系统数据字典类型", type = LogTypeEnum.QUERY, include = "")
    @RequestMapping(value = "/query", method = {RequestMethod.POST})
    public ResponseEntity<DatadicTypeVo> query(@ApiParam(value = "数据字典类别", required = true)
            @RequestParam(value = "dataDictTypeId") Long dataDictTypeId) throws SystemServiceException {
        DatadicTypePo po = datadicTypeService.queryWithValid(dataDictTypeId);
        DatadicTypeVo vo = CopyUtil.transfer(po, DatadicTypeVo.class);
        return getSuccessResult(vo);
    }

    @ApiOperation(value = "查询系统数据字典类型(code)", notes = "查询系统数据字典类型(code)", httpMethod = "GET")
    @Loggable(descp = "查询系统数据字典类型(code)", type = LogTypeEnum.QUERY, include = "")
    @RequestMapping(value = "/queryByCode", method = {RequestMethod.GET, RequestMethod.POST})
    public ResponseEntity<DatadicTypeVo> queryByCode(@ApiParam(value = "数据字典类别code", required = true)
             @RequestParam(value = "dataDictTypeCode") String dataDictTypeCode) throws SystemServiceException {
        DatadicTypeCondition condition = new DatadicTypeCondition();
        condition.setDataDictTypeCode(dataDictTypeCode);
        List<DatadicTypePo> poList = datadicTypeService.queryList(condition);
        if (poList.size() > 0) {
            DatadicTypeVo vo = CopyUtil.transfer(poList.get(0), DatadicTypeVo.class);
            return getSuccessResult(vo);
        }
        return getFailResult("未找到对应类型");
    }


    @ApiOperation(value = "查询系统数据字典类型数量", notes = "查询系统数据字典类型数量", httpMethod = "GET")
    @Loggable(descp = "查询系统数据字典类型数量", type = LogTypeEnum.QUERY, include = "")
    @RequestMapping(value = "/queryCount", method = {RequestMethod.GET, RequestMethod.POST})
    public ResponseEntity<Integer> queryCount(@ModelAttribute @Valid DatadicTypeQueryForm form) throws SystemServiceException {
        DatadicTypeCondition condition = this.getConditionByQueryForm(form);
        int count = datadicTypeService.queryCount(condition);
        return getSuccessResult(count);
    }

    @ApiOperation(value = "查询系统数据字典类型列表", notes = "查询系统数据字典类型列表", httpMethod = "GET")
    @Loggable(descp = "查询系统数据字典类型列表", type = LogTypeEnum.QUERY, include = "")
    @RequestMapping(value = "/queryList", method = {RequestMethod.GET, RequestMethod.POST})
    public ResponseEntity<CentreListResponse<DatadicTypeVo>> queryList(@ModelAttribute @Valid DatadicTypeQueryForm form) throws SystemServiceException {
        DatadicTypeCondition condition = this.getConditionByQueryForm(form);
        List<DatadicTypePo> poList = datadicTypeService.queryList(condition);
        List<DatadicTypeVo> voList = CopyUtil.transfer(poList, DatadicTypeVo.class);
        return getSuccessResult(getListResponse(voList));
    }

    @ApiOperation(value = "查询系统数据字典类型列表", notes = "查询系统数据字典类型列表", httpMethod = "GET")
    @Loggable(descp = "查询系统数据字典类型列表", type = LogTypeEnum.QUERY, include = "")
    @RequestMapping(value = "/querySelectList", method = {RequestMethod.GET, RequestMethod.POST})
    public ResponseEntity<CentreListResponse<DatadictSelectVo>> querySelectList() throws SystemServiceException {
        DatadicTypeCondition condition = new DatadicTypeCondition();
        condition.setPageSize(999);
        List<DatadicTypePo> poList = datadicTypeService.queryList(condition);
        List<DatadictSelectVo> selectVoList = new ArrayList<>();
        poList.forEach(data -> {
            DatadictSelectVo type = new DatadictSelectVo();
            type.setName(data.getDataDictTypeName());
            type.setValue(data.getDataDictTypeCode());
            selectVoList.add(type);
        });
        return getSuccessResult(getListResponse(selectVoList));
    }

    @ApiOperation(value = "查询系统数据字典类型列表(带分页)", notes = "查询系统数据字典类型列表(带分页)", httpMethod = "GET")
    @Loggable(descp = "查询系统数据字典类型列表(带分页)", type = LogTypeEnum.QUERY, include = "")
    @RequestMapping(value = "/queryPageList", method = {RequestMethod.GET, RequestMethod.POST})
    public ResponseEntity<CentreCutPageResponse<DatadicTypeVo>> queryPageList(@ModelAttribute @Valid DatadicTypeQueryForm form) throws SystemServiceException {
        DatadicTypeCondition condition = this.getConditionByQueryForm(form);
        List<DatadicTypeVo> voList = new ArrayList<>();
        int count = datadicTypeService.queryCount(condition);
        if (count > 0) {
            List<DatadicTypePo> poList = datadicTypeService.queryList(condition);
            voList = CopyUtil.transfer(poList, DatadicTypeVo.class);
        }
        return getSuccessResult(getPageResponse(form, count, voList));
    }
    @NeedRole("sysadminrole")
    @ApiOperation(value = "新增系统数据字典类型", notes = "新增系统数据字典类型", httpMethod = "POST")
    @Loggable(descp = "新增系统数据字典类型", type = LogTypeEnum.CREATE, include = "")
    @RequestMapping(value = "/add", method = {RequestMethod.GET, RequestMethod.POST})
    public ResponseEntity<DatadicTypeVo> add(@ModelAttribute @Valid DatadicTypeCreateForm form, HttpServletRequest request) throws SystemServiceException {
        DatadicTypePo po = CopyUtil.transfer(form, DatadicTypePo.class);
        po.setIsDefault(Constants.IS_NOT_DEFAULT);
        //判断是否存在相同的编码
        if (form.getDataDictTypeCode() != null) {
            DatadicTypeCondition codecondition = new DatadicTypeCondition();
            codecondition.setDataDictTypeCode(form.getDataDictTypeCode());
            int count = datadicTypeService.countByCodeorName(codecondition);
            if (count > 0) {
                return getFailResult("已存在相同的类型编码");
            }

        }
        //判断是否存在相同的名称
        if (form.getDataDictTypeName() != null) {
            DatadicTypeCondition codecondition = new DatadicTypeCondition();
            codecondition.setDataDictTypeName(form.getDataDictTypeName());
            int count = datadicTypeService.countByCodeorName(codecondition);
            if (count > 0) {
                return getFailResult("已存在相同的类型名称");
            }

        }
        datadicTypeService.insert(po);
        DatadicTypeVo vo = CopyUtil.transfer(po, DatadicTypeVo.class);
        return getSuccessResult(vo);
    }
    @NeedRole("sysadminrole")
    @ApiOperation(value = "修改系统数据字典类型", notes = "修改系统数据字典类型", httpMethod = "POST")
    @Loggable(descp = "修改系统数据字典类型", type = LogTypeEnum.UPDATE, include = "")
    @RequestMapping(value = "/update", method = {RequestMethod.GET, RequestMethod.POST})
    public ResponseEntity update(@ModelAttribute @Valid DatadicTypeUpdateForm form, HttpServletRequest request) throws SystemServiceException {
        DatadicTypePo po = CopyUtil.transfer(form, DatadicTypePo.class);
        //判断是否存在相同的编码
        if (form.getDataDictTypeCode() != null) {
            DatadicTypeCondition codecondition = new DatadicTypeCondition();
            codecondition.setId(form.getId());
            codecondition.setDataDictTypeCode(form.getDataDictTypeCode());
            int count = datadicTypeService.countByCodeorName(codecondition);
            if (count > 0) {
                return getFailResult("已存在相同的类型编码");
            }

        }
        //判断是否存在相同的名称
        if (form.getDataDictTypeName() != null) {
            DatadicTypeCondition codecondition = new DatadicTypeCondition();
            codecondition.setDataDictTypeName(form.getDataDictTypeName());
            codecondition.setId(form.getId());
            int count = datadicTypeService.countByCodeorName(codecondition);
            if (count > 0) {
                return getFailResult("已存在相同的类型名称");
            }

        }
        po.setUpdateTime(new Date());
        datadicTypeService.update(po);
        return getSuccessResult();
    }
    @NeedRole("sysadminrole")
    @ApiOperation(value = "删除系统数据字典类型", notes = "删除系统数据字典类型", httpMethod = "POST")
    @Loggable(descp = "删除系统数据字典类型", type = LogTypeEnum.DELETE, include = "")
    @RequestMapping(value = "/delete", method = {RequestMethod.GET, RequestMethod.POST})
    public ResponseEntity delete(@ModelAttribute @Valid @RequestParam(value = "id") List<Integer> id) throws SystemServiceException {
        if (id == null || id.size() == 0) {
            return getFailResult("参数错误");
        }
        for (int i = 0; i < id.size(); i++) {
            DatadicTypePo po = datadicTypeService.queryWithValid(id.get(i));
            if (po == null) {
                return getFailResult("您选择的记录不存在或已被删除");
            } else if (po.getIsDefault() == Constants.IS_DEFAULT) {
                //内置类型不允许删除
                return getFailResult("内置类型不允许删除");
            } else {
                //获取字典编码
                String dictTypeCode = po.getDataDictTypeCode();
                if (datadictService.selectCountByType(dictTypeCode) > 0) {
                    return getFailResult("此类型下有字典数据，不允许删除");
                }
            }
        }

        //删除字典类型记录
        datadicTypeService.batchDelete(id);

        return getSuccessResult();
    }

    private ResponseEntity batchDelete(List<Integer> idList) throws SystemServiceException {
        //根据ID数字查询是否存在内置数据类型
        DatadicTypeCondition defaultCondition = new DatadicTypeCondition();
        defaultCondition.setIsDefault(Constants.IS_DEFAULT);
        defaultCondition.setIdList(idList);
        int count = datadicTypeService.queryCount(defaultCondition);
        if (count > 0) {
            //如果ID列表包含内置对象,删除失败
            return getFailResult("您所选的对象包含内置对象，内置对象不能删除");
        } else {
            //删除字典类型记录
            datadicTypeService.batchDelete(idList);
            //查询字典类型code集合
            defaultCondition.setIsDefault(Constants.IS_NOT_DEFAULT);
            List<DatadicTypePo> datadicTypePoList = datadicTypeService.queryList(defaultCondition);
            if (datadicTypePoList != null && datadicTypePoList.size() > 0) {
                List<String> typeCodeList = datadicTypePoList.stream().map(DatadicTypePo::getDataDictTypeCode).collect(Collectors.toList());
                //删除关联的字典信息
                datadictService.batchDeleteByTypeCodeList(typeCodeList);
            }
        }
        return getSuccessResult();
    }


    /**
     * DatadicTypeQueryForm转换为DatadicTypeCondition
     *
     * @param form
     * @return
     */
    private DatadicTypeCondition getConditionByQueryForm(DatadicTypeQueryForm form) {
        DatadicTypeCondition condition = CopyUtil.transfer(form, DatadicTypeCondition.class);
        return condition;
    }

}